// 路由处理
const Router = require('express').Router()
// 引入model
const { Category } = require('../../model/categories')
const { Article } = require('../../model/article')

// 首页路由与分类路由
Router.get(['/', '/:cid'], async (req, res) => {
  // 读取数据库,获取分类数据
  const cate = await Category.find()
  // 获取文章数据
  let current = req.params.cid
  let options = {}
  if( current ){
    options.category = current
  }
  const articles =  await Article.find(options).populate('category author', 'name')
  console.log(articles)
  // 将数据传递给模板引擎
  res.render('index.html', {
    cate,
    current,
    articles
  })
})

// 文章页面路由
Router.get('/articles/:articleId', async (req, res) => {
  // 获取
  let articleId = req.params.articleId
  console.log(articleId, '======')
  // 读取数据库,获取分类数据
  const cate = await Category.find()
  // 通过文章iD获取文章信息
  let article = await Article.findById(articleId)
  res.render('article.html', {
    current: '',
    cate,
    article
  })
})

module.exports = Router
